package com.iSnail.ms.gather.biz;

import org.apache.log4j.Logger;

import com.iSnail.ms.gather.Context;
import com.iSnail.ms.gather.port.Port;
import com.iSnail.ms.gather.ui.MainFrame;
import com.iSnail.ms.util.Config;
import com.iSnail.ms.util.Const;
import com.iSnail.ms.util.I18N;

public class GatherThread extends Thread {
	private final static Logger log = Logger.getLogger(GatherThread.class.getName());

	Port read = new Port(Config.getConfigValue("read_port"));

	boolean flag = false;
	public GatherThread(){
		initPort();
	}

	private void initPort() {
		try {
			read.init();
			read.read();
		} catch (Throwable e) {
			log.warn("initPort ", e);
		}
	}

	public void run() {
		while (true) {
			try {
				if (Context.openstatus) {
					gather();
				} else {
					sleep(1000);
				}
			} catch (Throwable e) {
				log.warn("GatherThread ", e);
				MainFrame.setConsoleInfo(e.getLocalizedMessage());
			}
		}
	}

	private void gather() throws Throwable {
		read.statusChange();
		Thread.sleep(500);
		
		if (flag) {
			read.write(Const.START_COMMAND_PRESS);
			flag = false;
		} else {
			read.write(Const.START_COMMAND_TEMPER);
			flag = true;
		}
		
		Thread.sleep(500);
	}
	
	public static void setOpenstatus(boolean openstatus) {
		Context.openstatus = openstatus;
		if(openstatus){
			MainFrame.setConsoleInfo(I18N.getString("start_treenode"));
		}else{
			MainFrame.setConsoleInfo(I18N.getString("stop_treenode"));
		}
	}
	
	public static void main(String[] args) {
		new GatherThread().start();
	}
}